package data
{
	import event.GameEvent;
	
	import laya.events.Event;
	import laya.events.EventDispatcher;
	import laya.net.Socket;
	import laya.utils.Byte;

	public class SocketClient extends EventDispatcher
	{
		public var socket:Socket;
		private static  var _instance:SocketClient;
		private var output:Byte;
		private var message:*;
		public var socketSlow:Boolean=false;
		public function SocketClient()
		{
			if (_instance) {  
				throw new Error("只能用getInstance()来获取实例");  
			}
		}
		public static function getInstance():SocketClient {
			if(!_instance){
				_instance=new SocketClient();
			}
			return _instance;  
		}
		/**
		 *创建Socket链接 
		 * 
		 */		
		public function connectSocket():void
		{
			// TODO Auto Generated method stub
			//			Laya.timer.loop(50,this,sendData);
			socket=new Socket(); 
//			socket.connectByUrl(NumericalValueData.getInstance().webLocation["webLocation"]);
			socket.connectByUrl(NumericalValueData.getInstance().webLocation["loction"]);
//			socket.connectByUrl(NumericalValueData.getInstance().webLocation["publicLoction"]);
			socket.on(Event.OPEN, this, onSocketOpen);
			socket.on(Event.CLOSE, this, onSocketClose);
			socket.on(Event.MESSAGE, this, onMessageReveived); 	
			socket.on(Event.ERROR, this, onConnectError);
			output = socket.output;
		}
		private function onConnectError(e:*=null):void
		{
			// TODO Auto Generated method stub
			trace("error");
		}
		private function onMessageReveived(_message:*=null):void
		{
			// TODO Auto Generated method stub
			if (_message is String)
			{
				if(_message.length>0){
					readData(_message);
				}else{
//					trace("空消息"+_message);
				}
			}
			else if (_message is ArrayBuffer)
			{
				readData(new Byte(_message).readUTFBytes());
//				trace(new Byte(_message).readUTFBytes());
			}
			socket.input.clear();
		}
		
		private function onSocketClose(e:*=null):void
		{
			// TODO Auto Generated method stub
//			trace("Socket closed");
		}
		
		private function onSocketOpen(e:*=null):void
		{
			// TODO Auto Generated method stub
//			trace("Connected");
//			SocketData.getInstance().packetId=100;
//			SocketData.getInstance().radian=0.2351;
//			SocketData.getInstance().packetId=100;
//			SocketData.getInstance().rotate=-12;
//			SocketData.getInstance().x=0.4574;
//			SocketData.getInstance().y=0.7596;
			startCommunicate();
//			trace(JSON.stringify(SocketData.getInstance()))
//						socket.send(JSON.stringify(SocketData.getInstance()));
			
		}	
		public  var last:Number=new Date().getTime();
		private function readData(_message:*):void{
			message=JSON.parse(_message);
			switch(message["packetId"])
			{
				case NumericalValueData.getInstance().apiConfig["ON_CONNECTION_START"]:
				{
					
					break;
				}
					
				case NumericalValueData.getInstance().apiConfig["ON_CONNECTION_RECONNECT"]:
				{
					
					break;
				}
				case NumericalValueData.getInstance().apiConfig["ON_SET_NICKNAME"]:
				{
					
					break;
				}
				case NumericalValueData.getInstance().apiConfig["ON_SEND_CHAT_MESSAGE"]:
				{
					
					break;
				}
				case NumericalValueData.getInstance().apiConfig["ON_SET_PROTOCOL_VERSION"]:
				{
					
					break;
				}
				case NumericalValueData.getInstance().apiConfig["TO_CLEAR_MAP"]:
				{
					
					break;
				}
				case NumericalValueData.getInstance().apiConfig["TO_ADD_PLAYER"]:
				{
					SocketData.getInstance().objID=message["objectId"];
					SocketData.getInstance().player=message;
//					trace(JSON.stringify(message))
					event(GameEvent.TO_ADD_PLAYER);
					break;
				}
				case NumericalValueData.getInstance().apiConfig["ON_SET_TARGET"]:
				{
//					SocketData.getInstance().packetId=message["packetId"];
//					SocketData.getInstance().radian=message["radian"];
//					SocketData.getInstance().rotate=message["rotate"];
//					SocketData.getInstance().x=message["x"];
//					SocketData.getInstance().y=message["y"];
//					event(GameEvent.PLAYER_MOVE);
					break;
				}
				case NumericalValueData.getInstance().apiConfig["TO_UPDATE_MAP"]:
				{
					SocketData.getInstance().player=message["player"];
					SocketData.getInstance().enemy=message["enemy"];
					SocketData.getInstance().dead=message["dead"];
					SocketData.getInstance().nonVisible=message["nonVisible"];
					SocketData.getInstance().bullet=message["bullet"];
					SocketData.getInstance().exploded=message["exploded"];
					SocketData.getInstance().block=message["block"];
//					trace(JSON.stringify(SocketData.getInstance().bullet));
//					trace(JSON.stringify(message));
					if(SocketData.getInstance().isProcessorForEnemy){
						if(SocketData.getInstance().isProofForALL)return;
						SocketData.getInstance().isProcessorForEnemy=false;
						SocketData.getInstance().enemyPhoto=SocketData.getInstance().enemy;
						SocketData.getInstance().bulletPhoto=SocketData.getInstance().bullet;
						SocketData.getInstance().explodedPhoto=SocketData.getInstance().exploded;
						SocketData.getInstance().blockPhoto=SocketData.getInstance().block;
//						trace(JSON.stringify(SocketData.getInstance().blockPhoto));
						event(GameEvent.UPDATE_MAP);
					}
					var now:Number=new Date().getTime();
					SocketData.getInstance().pingStr="ping："+(now-last);
					if(now-last>=150){
						socketSlow=true;
					}else{
						socketSlow=false;
					}
					last=now;
					break;
				}
				case NumericalValueData.getInstance().apiConfig["ON_USE_PROPS"]:
				{
//					trace(JSON.stringify(_message));
					break;
				}
				case NumericalValueData.getInstance().apiConfig["TO_GAME_OVER"]:
				{
					trace("TO_GAME_OVER")
					alert("TO_GAME_OVER");
					break;
				}
				case NumericalValueData.getInstance().apiConfig["TO_GAME_TIME_OVER"]:
				{
					trace("TO_GAME_TIME_OVER");
					alert("TO_GAME_TIME_OVER");
					break;
				}
			}
		}
		
		private function softList(a:Object,b:Object):Number{
			return a["objectId"]-b["objectId"];
		}
		/**
		 * 开始通信
		 * 
		 */		
		public function startCommunicate():void{
			sendData(NumericalValueData.getInstance().apiConfig["ON_SET_PROTOCOL_VERSION"]);
		}
		public function sendData(packetId:Number,data:*=null):void
		{
			// TODO Auto Generated method stub
			switch(packetId)
			{
				case NumericalValueData.getInstance().apiConfig["ON_CONNECTION_START"]:
				{
					
					break;
				}
					
				case NumericalValueData.getInstance().apiConfig["ON_CONNECTION_RECONNECT"]:
				{
					
					break;
				}
				case NumericalValueData.getInstance().apiConfig["ON_SET_NICKNAME"]:
				{
					
					break;
				}
				case NumericalValueData.getInstance().apiConfig["ON_SEND_CHAT_MESSAGE"]:
				{
					
					break;
				}
				case NumericalValueData.getInstance().apiConfig["ON_SET_PROTOCOL_VERSION"]:
				{
					socket.send(JSON.stringify({"packetId":packetId,"protocolVersion":1}));
					break;
				}
				case NumericalValueData.getInstance().apiConfig["ON_SET_TARGET"]:
				{
					socket.send(JSON.stringify({"packetId":packetId,"radian":SocketData.getInstance().radian,"rotation":SocketData.getInstance().rotation,"x":SocketData.getInstance().x,"y":SocketData.getInstance().y}));
//					trace(JSON.stringify({"radian":SocketData.getInstance().radian,"rotation":SocketData.getInstance().rotation,"x":SocketData.getInstance().x,"y":SocketData.getInstance().y}));
					break;
				}
				case NumericalValueData.getInstance().apiConfig["ON_USE_PROPS"]:
				{
//					trace(JSON.stringify(data))
					socket.send(JSON.stringify(data));
					break;
				}
			}
			
		}
	}
}